package com.xs.project.service.impl;

import com.xs.project.cache.UserCacheMap;
import com.xs.project.common.Result;
import com.xs.project.mapper.XsCourseMapper;
import com.xs.project.pojo.vo.resp.*;
import com.xs.project.service.DataBoardService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class DataBoardServiceImpl implements DataBoardService {
    @Resource
    private XsCourseMapper xsCourseMapper;
    @Override
    public Result<DataBoardBaseResp> selectDataBoardBase() {
        Integer onlineNum = UserCacheMap.cacheMap.size();
        Integer teacherNum = xsCourseMapper.selectUserTeacherCount();
        Integer studentNum = xsCourseMapper.selectUserStudentCount();
        Integer courseNum = xsCourseMapper.selectCourseCount();
        Integer examNum = xsCourseMapper.selectExamCount();
        DataBoardBaseResp resp = new DataBoardBaseResp();
        resp.setOnlinePersonNum(onlineNum);
        resp.setRegisterTeacherNum(teacherNum);
        resp.setRegisterStudentNum(studentNum);
        resp.setCourseNum(courseNum);
        resp.setExamNum(examNum);
        return Result.success(resp);
    }

    @Override
    public Result<List<DataBoardExamList>> selectDataBoardExamList() {
        List<XsExamResp> list = xsCourseMapper.selectDataBoardExamList();
        Map<String, Long> dateCounts = list.stream()
                .map(XsExamResp::getExamTime)
                .map(date -> new SimpleDateFormat("MM-dd").format(date)) // 将Date转换为字符串，格式为"yyyy-MM-dd"
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        List<DataBoardExamList> listRes = new ArrayList<>();
        // 打印结果
        for (Map.Entry<String, Long> entry : dateCounts.entrySet()) {
            DataBoardExamList vo = new DataBoardExamList();
            vo.setExamTime(entry.getKey());
            vo.setExamNum(Integer.parseInt(String.valueOf(entry.getValue())));
            listRes.add(vo);
        }
        listRes.sort(Comparator.comparing(DataBoardExamList::getExamTime));
        return Result.success(listRes);
    }

    @Override
    public Result<List<StudentSelectCourse>> selectCoursePie() {
        List<StudentSelectCourse> list = xsCourseMapper.selectUserSelectCourse();
        int max = 0;
        for (StudentSelectCourse course : list) {
            max = max + course.getValue();
        }
        return Result.success(list);
    }
}
